package com.async_export_demo.export;

import com.async_export_demo.mapper.OrderMapper;
import com.async_export_demo.model.Order;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class OrderDataProvider implements DataProvider<Order> {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Page<Order> getPageData(long currentPage, long pageSize, AsyncExportService.ExportContext context) {
        Page<Order> queryPage = new Page<>(currentPage, pageSize);
        if (currentPage > 1) {
            // 分页总数只需要查询一次
            queryPage.setSearchCount(false);
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        // 只导出前100万
        queryWrapper.le("id", 4102093);
        if (currentPage > 1) {
            queryWrapper.gt("id", context.get("lastId"));
            queryPage.setCurrent(1);
        }
        Page<Order> result = orderMapper.selectPage(queryPage, queryWrapper);
        if (currentPage <= 1) {
            context.put("total", result.getTotal());
        } else {
            result.setTotal((Long) context.get("total"));
            result.setCurrent(currentPage);
        }
        // 加上上一次分页查询的最后一条数据id作为条件
        if (!Objects.isNull(result.getRecords()) && !result.getRecords().isEmpty()) {
            context.put("lastId", result.getRecords().get(result.getRecords().size() - 1).getId());
        }
        return result;
    }

    @Override
    public ExportEnum getType() {
        return ExportEnum.ORDER;
    }

    /**
     * 使用普通limit分页
     *
     * @param currentPage
     * @param pageSize
     * @param context
     * @return
     */
    public Page<Order> getPageData1(long currentPage, long pageSize, AsyncExportService.ExportContext context) {
        Page<Order> queryPage = new Page<>(currentPage, pageSize);
        if (currentPage > 1) {
            // 分页总数只需要查询一次
            queryPage.setSearchCount(false);
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        // 只导出前100万
        queryWrapper.le("id", 4102093);
        Page<Order> result = orderMapper.selectPage(queryPage, queryWrapper);
        if (currentPage <= 1) {
            context.put("total", result.getTotal());
        } else {
            result.setTotal((Long) context.get("total"));
        }
        return result;
    }
}
